package com.zou.activity.runner;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.*;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zouyaowen
 * @date 2020-10-13
 */
@Component
@Slf4j
public class SystemRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        Thread.sleep(10000);
        log.info("工作流开始执行");
        // 部署一个流程
        // 获取默认流程殷勤
        ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
        RepositoryService rs = engine.getRepositoryService();
        Deployment deploy = rs.createDeployment().addClasspathResource("processes/declare.bpmn").deploy();
        ProcessDefinition pd = rs.createProcessDefinitionQuery().deploymentId(deploy.getId()).singleResult();
        // 启动流程服务
        RuntimeService runtimeService = engine.getRuntimeService();
        // 启动当前流程
        ProcessInstance pi = runtimeService.startProcessInstanceById(pd.getId());
        // 当前流程id
        System.out.println(pi.getId());
        // 任务服务
        TaskService taskService = engine.getTaskService();
        // 当前流程的任务
        Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        Map<String,Object> map=new HashMap<>();
        // 用来判断当前流程是否通过，流程图中定义的判断条件  flag
        map.put("flag",true);
        // 完成当前节点任务，flag值用于进行判断
        taskService.complete(task.getId(),map);
        System.out.println("完成第一个节点任务:任务id"+task.getId()+"____  流程实例ID:"+pi.getId());
        // 获取第二个节点信息
        Task task1 = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        System.out.println("流程实例ID:"+task1.getProcessInstanceId()+"___任务ID:"+task1.getId()+"____任务名称:"+task1.getName());
        Map<String,Object> map1=new HashMap<>();
        // 用来判断当前流程是否通过，流程图中定义的判断条件  flag
        map1.put("flag",true);
        // 完成当前节点任务，flag值用于进行判断
        taskService.complete(task1.getId(),map1);
        System.out.println("完成第二个节点任务:任务id"+task1.getId()+"____  流程实例ID:"+pi.getId());
        // 获取第三个节点信息
        Task task2 = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        System.out.println("流程实例ID:"+task2.getProcessInstanceId()+"___任务ID:"+task2.getId()+"____任务名称:"+task2.getName());
        taskService.complete(task2.getId());
        System.out.println("完成任务");

    }
}
